#INCLUDE "PROTHEUS.CH"

USER FUNCTION AtuRegCli()

Processa({|| ProcRot()}, "Atualizando Dados", "Aguarde...")

RETURN NIL

//-----------------------------------------------------------------
STATIC FUNCTION ProcRot()
LOCAL aArea := GetArea()
LOCAL aDUYArea := DUY->(GetArea())
LOCAL aSA1Area := SA1->(GetArea())
LOCAL cCodMun := ""
LOCAL cGrpVen := ""
LOCAL cCodCli := ""

dbSelectArea("SA1")
SA1->(dbSetOrder(1)) // A1_FILIAL+A1_COD+A1_LOJA
SA1->(dbGoTop())

dbSelectArea("DUY")
DUY->(dbSetOrder(6))  // DUY_FILIAL+DUY_EST+DUY_CODMUN

ProcRegua(SA1->(RecCount()))

WHILE !SA1->(EOF())
	IncProc()
	cCodCli := SA1->A1_COD + SA1->A1_LOJA
	
	IF DUY->(dbSeek(xFilial("DUY") + SA1->(A1_EST + A1_COD_MUN)))
		cCodMun := DUY->(DUY_EST+DUY_CODMUN)
		cGrpVen := DUY->DUY_GRPVEN
		DUY->(dbSkip())
		
		WHILE !DUY->(EOF()) .And. DUY->(DUY_EST + DUY_CODMUN) == cCodMun 
			IF !EMPTY(DUY->DUY_GRPSUP)
				cGrpVen := DUY->DUY_GRPVEN
			ENDIF
			DUY->(dbSkip())
		END WHILE
		
		IF !EMPTY(cGrpVen)
			SA1->(RecLock("SA1", .F.))
				SA1->A1_CDRDES := cGrpVen
			SA1->(MsUnlock())
		ENDIF
	ENDIF
	SA1->(dbSkip())
END WHILE

SA1->(dbCloseArea())
DUY->(dbCloseArea())
RestArea(aArea)
RestArea(aSA1Area)
RestArea(aDUYArea)

RETURN NIL

//-----------------------------------------------------------------